<template>
<el-upload
    :on-preview="preview"
    :on-remove="handleRemove"
    :on-change="changeFile"
    :before-upload="beforeUpload"
    :file-list="fileList"
    :http-request="upload"
    list-type="picture-card"
    action="#"
    :limit="1"
    :class="{disabled: fileComputed }"
>
    <div slot="file" slot-scope="{file}" style="width: 100%; height:100% ;">
        <el-image
            style="width: 100%; height:100% ;"
            :src="file.url"
            fit="cover"
        ></el-image>
        <span class="el-upload-list__item-actions">
            <span
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
            >
                <i class="el-icon-delete"></i>
            </span>
        </span>
    </div>
    <i class="el-icon-plus" />
</el-upload>
</template>

<script>
import COS from 'cos-js-sdk-v5' // 引入腾讯云的包
// 需要实例化
// 实例化的包 已经具有了上传的能力 可以上传到该账号里面的存储桶了
const cos = new COS({
	SecretId: 'AKIDNZVBaiY8RTEiwub1A2dy3rOecJjupUsz',
	SecretKey: 'rSmpb6LJ0RbU6QU5PSEjxtYx4wXswnNg'
})
export default {
	props: {
		type: {
			type: String,
			required: true
		}
	},
	data() {
		return {
			userId: this.$route.params.id,
			fileList: [],
			/* 记住当前上传的图片id */
			nowID: ''
		}
	},
	computed: {
		fileComputed() {
			return this.fileList.length === 1
		}
	},
	created() {
		console.log(this.userId)
	},
	methods: {
		preview(file) {},
		/* 删除本地显示 */
		handleRemove(file) {
			this.fileList = this.fileList.filter(item => item.uid !== file.uid)
		},
		/* 删除云数据 */
		sureRemove() {
			cos.deleteObject({
				Bucket: 'human-resources-1305779664',
				Region: 'ap-guangzhou',
				Key: this.userId + this.type
			})
		},
		changeFile(file, fileList) {
			this.fileList = fileList.map(item => item)
			// console.log(this.fileList)
		},
		beforeUpload(file) {
			// 限制上传格式
			const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
			if (!types.includes(file.type)) {
				this.$message.error('上传图片只能是 JPG、GIF、BMP、PNG 格式!')
				return false
			}
			const maxSize = 5 * 1000 * 1000
			if (file.size > maxSize) {
				this.$message.error('上传图片不得超过 5M ！')
				return false
			}
			this.nowID = file.uid
		},
		upload(params) {
			if (params.file) {
				cos.putObject({
					Bucket: 'human-resources-1305779664',
					Region: 'ap-guangzhou',
					// 文件名作为key
					Key: this.userId + this.type,
					// 此类写死
					StorageClass: 'STANDARD',
					// 将本地的文件赋值给腾讯云配置
					Body: params.file
				}, (err, data) => {
					// console.log(err, data)
					// 没有错误信息，并且返回状态码200
					if (!err && data.statusCode === 200) {
						this.fileList = this.fileList.map(item => {
							if (item.uid === this.nowID) {
								return { url: 'http://' + data.Location, upload: true }
							}
							return item
						})
					}
				})
			}
		}
	}
}
</script>

<style>
	.disabled .el-upload--picture-card {
		display: none
	}
</style>
